package com.xlongwei.info;

import static io.undertow.Handlers.path;

import org.xnio.IoUtils;

import com.networknt.config.JsonMapper;
import com.networknt.handler.HandlerProvider;
import com.xlongwei.info.handler.MyBodyHandler;
import com.xlongwei.info.handler.StaticResourceHandler;
import com.xlongwei.info.hook.Shutdown;
import com.xlongwei.info.util.Utils;

import io.undertow.server.HttpHandler;

public class WebServerHandlerProvider implements HandlerProvider {
	public WebServerHandlerProvider() {
		Shutdown.addRuntime(new Runnable() {
			@Override
			public void run() {
				Utils.sse.getConnections().forEach(conn -> {
					IoUtils.safeClose(conn);
				});
			}
		});
	}

	public HttpHandler getHandler() {
		MyBodyHandler bodyHandler = new MyBodyHandler();
		bodyHandler.setNext(path().addPrefixPath("/json", new JsonHandler(JsonMapper.objectMapper))
				.addPrefixPath("/text", new TextHandler()));
		return path().addPrefixPath("/api", bodyHandler).addPrefixPath("/sse", Utils.sse).addPrefixPath("/",
				new StaticResourceHandler());
	}

}
